/*
	Copyright (c) 2009, M.P. Bartnig & A. Gosman
	
	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:
	
	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.
	
	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
package nl.sanity.ui
{
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.geom.Rectangle;
	
	import nl.sanity.events.UIEvent;
	import nl.sanity.ui.helpers.DisplayState;
	import nl.sanity.ui.helpers.UIAlign;
	import nl.sanity.utils.DisplayUtils;
	
	import org.bytearray.display.ScaleBitmap;
	
	/**
	 * BaseComponent
	 *
	 * @langversion ActionScript 3
	 *
	 * @author M.P. Bartnig
	 * @since  16/03/2009
	 */
	public class BaseComponent extends Sprite
	{
		// --- CONSTRUCTOR ----------------------------------------
		
		protected var _width					:Number;
		protected var _height					:Number;
		protected var _alignment				:UIAlign;
		protected var _scalable					:Boolean;
		protected var _enabled					:Boolean;
		protected var _isDrawn					:Boolean;
		protected var _hasFocus					:Boolean;
		protected var _verbose					:Boolean;
		
		protected var _currentDisplayState		:DisplayObject;
		protected var _currentState				:String;
		protected var _defaultState				:String;			
		protected var _requiredStates			:Array;
		protected var _states					:Array;
		
		public function BaseComponent( parent:DisplayObjectContainer = null, posX:Number = 0, posY:Number = 0, scalable:Boolean = false, verbose:Boolean = false )
		{
			_verbose 		= verbose;
			
			moveTo( posX, posY );
			 
			if ( parent )
			{
				parent.addChild( this );
			}
			
			_scalable 	= scalable;
			
			init();
		}
		
		// --- PUBLIC FUNCTIONS -----------------------------------------

		public function draw():void
		{
			_isDrawn 		= true;
			
			dispatchEvent( new UIEvent( UIEvent.DRAW ) );
		}
		
		public function setSize( newWidth:Number, newHeight:Number ):void
		{
			width	= newWidth;
			height	= newHeight;
		}
		
		public function moveTo( posX:Number = 0, posY:Number = 0 ):void
		{
			x	= Math.round( posX );
			y	= Math.round( posY );
		}
		
		public function setState( stateType:String, displayObject:DisplayObject ):void
		{
			_states[ stateType ] = displayObject;
			
			invalidate();
		}
		
		public function setStateMap( bitmap:Bitmap, scale9Grid:Rectangle = null, smoothing:Boolean = false, sliceOrientation:String = "vertical" ):void
		{
			sliceStateMap( new Bitmap( bitmap.bitmapData.clone() ), scale9Grid, smoothing, sliceOrientation );
			
			invalidate();
		}
		
		public function updateFocusRect( filters:Array = null ):void
		{
			// Only put filters on a displaystate, not on labels, etc.
			if ( _currentDisplayState )
			{
				_currentDisplayState.filters = filters;
			}
		}
		
		// Accessor for immediate displaylist updates 
		public function updateNow():void
		{
			if ( hasEventListener( Event.ENTER_FRAME ) )
			{
				removeEventListener( Event.ENTER_FRAME, onInvalidate );
			}
			
			draw();
		}
		
		// --- PROTECTED FUNCTIONS ----------------------------------------
		
		protected function init():void
		{
			_states		= new Array();
			
			_width		= 0;
			_height 	= 0;
			
			addChildren();
			addAddedToStageListener();
			addEventListeners();
			
			// Disable default Flash focusRect
			focusRect = false;
			
			invalidate();
		}
		
		protected function addChildren():void
		{
			// Implementation in subclasses
		}
		
		protected function setRequiredStates():void
		{
			// Implementation in subclasses
		}
		
		protected function onFocusIn( event:FocusEvent ):void
		{
			_hasFocus = true;
			
			// Rest of implementation in subclasses
		}
		
		protected function onFocusOut( event:FocusEvent ):void
		{
			_hasFocus = true;
			
			// Rest of implementation in subclasses
		}
		
		protected function addEventListeners():void
		{
			addEventListener( FocusEvent.FOCUS_IN, onFocusIn, false, 0, true );
			addEventListener( FocusEvent.FOCUS_OUT, onFocusOut, false, 0, true );
		}
		
		protected function removeEventListeners():void
		{
			removeEventListener( FocusEvent.FOCUS_IN, onFocusIn );
			removeEventListener( FocusEvent.FOCUS_OUT, onFocusOut );
			
			if ( hasEventListener( Event.ENTER_FRAME ) )
			{
				removeEventListener( Event.ENTER_FRAME, onInvalidate );
			}
		}
		
		protected function onAddedToStage( event:Event ):void
		{
			addRemovedFromStageListener();
		}
		
		protected function onRemovedFromToStage( event:Event ):void
		{
			dispose();
			addAddedToStageListener();
		}
		
		protected function addAddedToStageListener():void
		{
			addEventListener( Event.ADDED_TO_STAGE, onAddedToStage, false, 0, true );
			removeEventListener( Event.REMOVED_FROM_STAGE, onRemovedFromToStage );
		}
		
		protected function addRemovedFromStageListener():void
		{
			addEventListener( Event.REMOVED_FROM_STAGE, onRemovedFromToStage, false, 0, true );
			removeEventListener( Event.ADDED_TO_STAGE, onAddedToStage );
		}
		
		protected function dispose():void
		{
			removeEventListeners();
		}
		
		protected function invalidate():void
		{
			addEventListener( Event.ENTER_FRAME, onInvalidate, false, 1, true );
		}
		
		protected function onInvalidate( event:Event = null ):void
		{
			removeEventListener( Event.ENTER_FRAME, onInvalidate );
			draw();
		}
		
		protected function numStates():uint
		{
			var numStates:uint = 0;
			
			for ( var n:* in _states )
			{
				numStates++;
			}
			
			return numStates;
		}
		
		protected function sliceStateMap( bitmap:Bitmap, scale9Grid:Rectangle = null, smoothing:Boolean = false, sliceOrientation:String = "vertical" ):void
		{
			var stateType:String;
			var sourceRect:Rectangle;
			var bitmapSlice:Bitmap;
			var scaledBitmapSlice:ScaleBitmap;
			
			if ( sliceOrientation == "vertical" )
			{
				var stateHeight:Number = Math.round( bitmap.height / _requiredStates.length );
			}
			else if ( sliceOrientation == "horizontal" )
			{
				var stateWidth:Number = Math.round( bitmap.width / _requiredStates.length );
			}
			
			for ( var i:uint = 0; i < _requiredStates.length; i++ )
			{
				stateType = _requiredStates[ i ];
				
				if ( sliceOrientation == "vertical" )
				{
					sourceRect = new Rectangle( 0, ( i * stateHeight ), bitmap.width, stateHeight );
				}
				else if ( sliceOrientation == "horizontal" )
				{
					sourceRect = new Rectangle( ( i * stateWidth ), 0, stateWidth, bitmap.height );
				}
				
				bitmapSlice	= DisplayUtils.getBitmapSlice( bitmap, sourceRect );
				
				if ( _scalable )
				{
					scaledBitmapSlice = new ScaleBitmap( bitmapSlice.bitmapData );
				
					if ( scale9Grid )
					{
						scaledBitmapSlice.scale9Grid = scale9Grid;
					}
					
					_width 	= _width || scaledBitmapSlice.width;
					_height = _height || scaledBitmapSlice.height;
					
					scaledBitmapSlice.smoothing = smoothing;
					
					scaledBitmapSlice.setSize( _width, _height );
					
					_states[ stateType ] = scaledBitmapSlice;
				}
				else
				{
					_width					= bitmapSlice.width;
					_height					= bitmapSlice.height;
					bitmapSlice.smoothing	= smoothing;
					
					_states[ stateType ]	= bitmapSlice;
				}
			}
		}
		
		protected function addDisplayState( newDisplayState:DisplayObject ):void
		{
			if ( _currentDisplayState == newDisplayState ) return;
			
			if ( _currentDisplayState && contains( _currentDisplayState ) )
			{
				_currentDisplayState.filters = [];
				removeChild( _currentDisplayState );
			}
			
			_currentDisplayState 		= newDisplayState;
			
			if ( _scalable )
			{
				_currentDisplayState.width	= _width;
				_currentDisplayState.height	= _height;
			}
			
			addChildAt( _currentDisplayState, 0 );
			
			if ( _hasFocus )
			{
				updateFocusRect();
			}
		}
		
		protected function updateDisplayState():void
		{
			switch ( _currentState )
			{
				case DisplayState.UP:
					if ( _states[ _currentState ] )
					{
						addDisplayState( _states[ _currentState ] );
					}
					else
					{
						throw new Error( "Display object for state '" + _currentState + "' not found..." );
					}
					break;
				
				case DisplayState.OVER:
				case DisplayState.DOWN:
				case DisplayState.DISABLED:
				case DisplayState.SELECTED_UP:
				case DisplayState.SELECTED_OVER:
				case DisplayState.SELECTED_DOWN:
				case DisplayState.SELECTED_DISABLED:
				case DisplayState.ENABLED:
					if ( _states[ _currentState ] )
					{
						addDisplayState( _states[ _currentState ] );
					}
					else
					{
						addDefaultDisplayState();
					}
					break;
			}
			
			if ( _scalable )
			{
				_currentDisplayState.width	= _width;
				_currentDisplayState.height = _height;
			}
		}
		
		protected function addDefaultDisplayState():void
		{
			if ( _defaultState && _states[ _defaultState ] )
			{
				addDisplayState( _states[ _defaultState ] );
			}
			else
			{
				throw new Error( "Display object for state '" + _currentState + "' not found and there's no default..." );
			}
		}
		
		// --- GETTER/SETTER ----------------------------------------

		override public function get width():Number
		{
			return _width;
		}
		override public function set width( value:Number ):void
		{
			_width		= value;
			invalidate();
			dispatchEvent( new Event( Event.RESIZE ) ); 
		}
		
		override public function get height():Number
		{
			return _height;
		}
		override public function set height( value:Number ):void
		{
			_height		= value;
			invalidate();
			dispatchEvent( new Event( Event.RESIZE ) ); 
		}
		
		override public function set x( value:Number ):void
		{
			super.x	= Math.round( value );
		}
		
		override public function set y( value:Number ):void
		{
			super.y	= Math.round( value );
		}
		
		public function get enabled():Boolean
		{
			return _enabled;
		}
		public function set enabled( value:Boolean ):void
		{
			_enabled 			= value;
			
			mouseEnabled     	= _enabled;
			tabEnabled			= _enabled;
			invalidate();
		}
		
		public function get alignment():UIAlign
		{
			return _alignment;
		}
		public function set alignment( value:UIAlign ):void
		{
			_alignment = value;
			invalidate();
		}
		
		public function get scalable():Boolean
		{
			return _scalable;
		}
		public function set scalable( value:Boolean ):void
		{
			_scalable = value;
			invalidate();
		}
	}
}